home *** CD-ROM | disk | FTP | other *** search
- Path: news.minn.net!news
- From: gruch@minn.net
- Newsgroups: comp.lang.c
- Subject: Re: Array indexing with malloc
- Date: Sat, 20 Apr 1996 13:02:03 GMT
- Organization: Minn Net
- Message-ID: <4lan7j$1op@cobra.Minn.Net>
- References: <96110.093936F0O@psuvm.psu.edu>
- NNTP-Posting-Host: dialup-198.minn.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- Tim Benner <F0O@psuvm.psu.edu> wrote:
-
- > I write c programs to collect online data, and I always malloc a block
- >of memory to hold the data. I set the memory block up such that each
- >row is a different time point, and each column is a different channel.
- > The formula I use to do this is:
- > RawData[CurrentPoint*NumChannels+Channel]
- > This works fine, except I don't like having to do the multiplication
- >every time I want to access a point in the memory block. I tried setting
- >up the memory block by mallocing a structure. This also works, and I
- >believe is neater in implementation, but seems to have a limit of about
- >64k. I allocate arrays of around 100k or more.
- > My burning question is, can I use a structure rather then the above
- >method for accessing large arrays? I'm using Turbo C++ version 3.0, and
- >I'm in the large memory model. I'm also setting the pointer to memory
- >as a far huge pointer.
-
- >[Tim]
-
- A couple of things.
- First your 64k problem. malloc has a 64k size limit. To allocate a
- huge array you must use halloc. The compilers I've used (i'm not
- certain that this is true in all compilers) require huge arrays
- allocated with halloc larger than 128k to have an elelment size that
- is a power of 2. Therefore the statement-
-
- ptr = halloc(1000, 3); // 1000 elements at 3 bytes- total 3000 bytes
-
- is illegal. But-
-
- ptr = halloc(750, 4); // 750 elements at 4 bytes- total 3000 bytes
-
- is legal. That should take care of your size limit problem.
-
- Second is the multiplication to access the data. Why not use a 2
- dimensional array? It's a little more overhead setting it up but
- worth the effort for speeds sake. My solution looks something like
- this- (just a quick hack with little error checking)-
-
- // Set up dynamic 2 dimensional array
- void make_array(int x_dim, int y_dim)
- {
- int **ptr; // Assuming a dual array of ints
-
- // Allocate x dimension.
- ptr = halloc(x_dim, sizeof(int)); // Assuming int is 2 or 4
- bytes
-
- // Allocate y dimension
- for(indx = 0; indx < y_dim; indx++)
- ptr[indx] = halloc(y_dim, sizeof(int));
- }
-
- // Have to free the array
- void free_array(int x_dim, int y_dim)
- {
- int indx;
-
- // Free y dimension
- for(indx = 0; indx < y_dim; indx++)
- hfree(ptr[indx]);
-
- // Free x dimension
- hfree(ptr);
- }
-
- Now any point in your array can be accessed very easily by-
-
- data = ptr[x][y];
-
- instead of the single dimensional model-
-
- data = ptr[x*x_dim+y];
-
- Hope this helps.
- ~Gerry
-
-